package tk.hongbo.socket;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;

import javax.websocket.*;
import javax.websocket.server.PathParam;
import javax.websocket.server.ServerEndpoint;
import java.io.IOException;

@ServerEndpoint("/myWs/{name}")
@Component
public class WebSocket {

    private static final Logger logger = LoggerFactory.getLogger(WebSocket.class);

    @OnOpen
    public void onOpen(@PathParam(value = "name") String name, Session session) throws IOException {
        if (name != null && !name.equals("")) {
            logger.debug("名称合法，添加到Map中");
            SocketManager.put(name, session);
        } else {
            logger.debug("关闭连接");
            session.close();
        }
    }

    @OnMessage
    public void onMessage(String message) {
        logger.debug("接收到消息 {}", message);
    }

    @OnError
    public void onError(@PathParam(value = "name") String name, Throwable throwable) {
        logger.error("连接发生错误 {}", throwable.getMessage());
        SocketManager.remove(name);
    }

    @OnClose
    public void onClose(@PathParam(value = "name") String name) {
        logger.debug("关闭连接");
        SocketManager.remove(name);
    }

    /*
    使用在线网址测试
    http://coolaf.com/tool/chattest
     */
}
